<template>
  <div class="player-manage">
    <h2>玩家管理</h2>

    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
          v-model="searchQuery"
          placeholder="请输入账号或昵称"
          clearable
          style="width: 300px"
          @clear="onSearchClear"
      />
      <el-button type="primary" @click="onSearch">搜索</el-button>
    </div>

    <!-- 玩家表格 -->
    <el-table :data="players.records" style="width: 100%" border v-loading="loading">
      <el-table-column
          prop="id"
          label="ID"
          align="center"
          :sortable="true"
          @sort-change="handleSortChange">
      </el-table-column>
      <el-table-column
          prop="account"
          label="账号"
          align="center"
          :sortable="true"
          @sort-change="handleSortChange">
      </el-table-column>
      <el-table-column
          prop="nickname"
          label="昵称"
          align="center"
          :sortable="true"
          @sort-change="handleSortChange">
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          :sortable="true"
          @sort-change="handleSortChange">
      </el-table-column>
      <el-table-column
          prop="lastLoginTime"
          label="最后登录时间"
          align="center"
          :sortable="true"
          @sort-change="handleSortChange">
      </el-table-column>
      <el-table-column label="公会" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showGuild(scope.row)">查看公会</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="players.page"
        :page-sizes="[10, 20, 50]"
        :page-size="players.rows"
        layout="total, sizes, prev, pager, next, jumper"
        :total="players.total"
        style="margin-top: 20px"
    ></el-pagination>

    <el-button type="primary" @click="showAddPlayerDialog">新增玩家</el-button>

    <!-- 新增玩家对话框 -->
    <el-dialog title="新增玩家" v-model="addPlayerDialogVisible" width="30%">
      <el-form :model="newPlayer">
        <el-form-item label="账号">
          <el-input v-model="newPlayer.account"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="newPlayer.nickname"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="newPlayer.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="newPlayer.createTime"
              type="datetime"
              placeholder="选择创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addPlayerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addPlayer">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑玩家对话框 -->
    <el-dialog title="编辑玩家" v-model="editPlayerDialogVisible" width="30%">
      <el-form :model="currentPlayer">
        <el-form-item label="账号">
          <el-input v-model="currentPlayer.account" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="currentPlayer.nickname"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="currentPlayer.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最后登录时间">
          <el-date-picker
              v-model="currentPlayer.lastLoginTime"
              type="datetime"
              placeholder="选择最后登录时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editPlayerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updatePlayer">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 玩家公会对话框 -->
    <el-dialog title="玩家公会" v-model="guildDialogVisible" width="50%">
      <el-table :data="playerGuilds" style="width: 100%" border>
        <el-table-column prop="id" label="公会ID" align="center"></el-table-column>
        <el-table-column prop="name" label="公会名称" align="center"></el-table-column>
        <el-table-column prop="position" label="职位" align="center"></el-table-column>
        <el-table-column prop="joinTime" label="加入时间" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.joinTime) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="guildDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

// 数据定义 - 适配后端分页结构
const players = ref({
  page: 1,
  rows: 10,
  total: 0,
  records: []
});
const searchQuery = ref("");
const loading = ref(false);

// 排序状态
const sortState = ref({
  prop: '',
  order: ''
});

const newPlayer = ref({
  account: "",
  nickname: "",
  status: 1,
  createTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
});
const currentPlayer = ref({});
const addPlayerDialogVisible = ref(false);
const editPlayerDialogVisible = ref(false);

// 公会管理相关状态
const guildDialogVisible = ref(false);
const playerGuilds = ref([]);
const currentPlayerForGuild = ref({});

// 获取玩家列表
const getPlayers = async () => {
  loading.value = true;
  try {
    console.log('Request params:', {
      keyword: searchQuery.value,
      page: players.value.page,
      pageSize: players.value.rows,
      sortField: sortState.value.prop,
      sortOrder: sortState.value.order === 'ascending' ? 'asc' : 'desc'
    });

    const res = await request.get("/player/list", {
      params: {
        keyword: searchQuery.value,
        page: players.value.page,
        pageSize: players.value.rows,
        sortField: sortState.value.prop,
        sortOrder: sortState.value.order === 'ascending' ? 'asc' : 'desc'
      }
    });

    if (res.code === 200) {
      players.value = res.data || { page: 1, rows: 10, total: 0, records: [] };
      console.log('Fetched players:', players.value);
    } else {
      ElMessage.error(res.message || "获取玩家列表失败");
    }
  } catch (error) {
    console.error("获取玩家列表出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getPlayers();
});

// 分页事件
function handleSizeChange(size) {
  players.value.rows = size;
  getPlayers();
}

function handleCurrentChange(page) {
  players.value.page = page;
  getPlayers();
}

// 搜索相关
function onSearch() {
  players.value.page = 1; // 重置到第一页
  getPlayers();
}

function onSearchClear() {
  searchQuery.value = '';
  players.value.page = 1; // 重置到第一页
  getPlayers();
}

// 新增玩家相关逻辑
const showAddPlayerDialog = () => {
  newPlayer.value = {
    account: "",
    nickname: "",
    status: 1,
    createTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
  };
  addPlayerDialogVisible.value = true;
};

const addPlayer = async () => {
  try {
    const res = await request.post("/player", newPlayer.value);
    if (res.code === 200) {
      ElMessage.success("新增玩家成功");
      await getPlayers();
      addPlayerDialogVisible.value = false;
      newPlayer.value = {
        account: "",
        nickname: "",
        status: 1,
        createTime: null
      };
    } else {
      ElMessage.error(res.message || "新增玩家失败");
    }
  } catch (error) {
    console.error("新增玩家出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
  }
};

// 编辑玩家相关逻辑
const handleEdit = (row) => {
  // 格式化时间字段，确保lastLoginTime为可编辑格式
  currentPlayer.value = {
    ...row,
    lastLoginTime: row.lastLoginTime ? dayjs(row.lastLoginTime).format("YYYY-MM-DD HH:mm:ss") : null
  };
  editPlayerDialogVisible.value = true;
};

const updatePlayer = async () => {
  try {
    // 修改时间格式为 YYYY-MM-DD HH:mm:ss，匹配数据库格式
    if (currentPlayer.value.lastLoginTime) {
      currentPlayer.value.lastLoginTime = dayjs(currentPlayer.value.lastLoginTime)
          .format("YYYY-MM-DD HH:mm:ss");
    }

    const res = await request.put("/player", currentPlayer.value);
    if (res.code === 200) {
      ElMessage.success("更新玩家成功");
      await getPlayers();
      editPlayerDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || "更新玩家失败");
    }
  } catch (error) {
    console.error("更新玩家出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
  }
};

// 删除玩家相关逻辑
const handleDelete = async (id) => {
  if (confirm(`确定要删除该玩家吗？`)) {
    try {
      const res = await request.delete(`/player/${id}`);
      if (res.code === 200) {
        ElMessage.success("删除玩家成功");
        await getPlayers();
      } else {
        ElMessage.error(res.message || "删除玩家失败");
      }
    } catch (error) {
      console.error("删除玩家出错:", error);
      ElMessage.error("网络请求失败，请检查控制台日志");
    }
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "从未登录";
  try {
    return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
  } catch (e) {
    return "时间格式错误";
  }
};

// 公会管理相关逻辑
const showGuild = async (player) => {
  currentPlayerForGuild.value = { ...player };
  await loadPlayerGuilds(player.id);
  guildDialogVisible.value = true;
};

const loadPlayerGuilds = async (playerId) => {
  try {
    const res = await request.get(`/player/${playerId}/guilds`);
    if (res.code === 200) {
      playerGuilds.value = res.data;
    } else {
      ElMessage.error(res.message || "获取玩家公会失败");
      playerGuilds.value = [];
    }
  } catch (error) {
    console.error("获取玩家公会出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
    playerGuilds.value = [];
  }
};

// 排序事件处理
const handleSortChange = ({ prop, order }) => {
  sortState.value.prop = prop;
  sortState.value.order = order;
  getPlayers();
};
</script>

<style scoped>
.player-manage {
  padding: 20px;
}

/* 表格样式增强 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  text-align: center;
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  text-align: center;
  padding: 12px 0;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
</style>